<template>
	<view class="flex flex-column" style="height: 100vh;">
		<view><u-tabs-swiper ref="uTabs" :list="list" :current="current" @change="tabsChange" :is-scroll="false" swiperWidth="750"></u-tabs-swiper></view>
		<swiper :current="swiperCurrent" @transition="transition" @change="swiperChange" @animationfinish="animationfinish" class="flex-1">
			<swiper-item class="swiper-item" v-for="(item, idx) in list" :key="idx">
				<scroll-view scroll-y style="width: 100%;" @scrolltolower="onreachBottom">
					<view v-for="(post, index) in posts" :key="index" @click="openDetail(post)">
						<view class="p-2">
							<view class="font-md u-line-3 mb-2 text-dark" style="font-weight: 500;">{{ post.title.rendered }}</view>
							<u-image :src="post.articleInfor.thumbnail" mode="widthFix" style="max-height: 200rpx;" class="rounded"></u-image>
							<view class="flex text-light-muted">
								<view class="mr-1">{{post.articleInfor.classify[0].cat_name}}</view>
								<view class="mr-1">{{post.articleInfor.viewCount}} 观看</view>
								<view>{{$dayjs(post.modified).format('YYYY-MM-DD')}}</view>
							</view>
						</view>
						
						<u-gap v-if="index < posts.length -1" height="20" bg-color="#e5e5e5"></u-gap>
					</view>
				</scroll-view>
			</swiper-item>
		</swiper>
	</view>
</template>

<script>
import { getPosts } from '@/api/posts.js';
import { getCategories } from '@/api/categories.js';
export default {
	data() {
		return {
			categories: [],
			posts: [],
			list: [],
			// 因为内部的滑动机制限制，请将tabs组件和swiper组件的current用不同变量赋值
			current: 0, // tabs组件的current值，表示当前活动的tab选项
			swiperCurrent: 0 // swiper组件的current值，表示当前那个swiper-item是活动的
		};
	},
	async onLoad() {
		const categories = await getCategories({
			params: {
				parent: '0'
			}
		});
		const posts = await getPosts({
			params: {
				categories: categories[0].id
			}
		});
		this.list = categories.map(item => {
			return {
				id: item.id,
				name: item.name
			};
		});
		this.posts = posts;
	},
	methods: {
		// tabs通知swiper切换
		async tabsChange(index) {
			this.posts = [];
			this.swiperCurrent = index;
			const posts = await getPosts({
				params: {
					categories: this.list[index].id
				}
			});
			this.posts = posts;
		},
		// swiper-item左右移动，通知tabs的滑块跟随移动
		transition(e) {
			let dx = e.detail.dx;
			this.$refs.uTabs.setDx(dx);
		},
		// 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
		// swiper滑动结束，分别设置tabs和swiper的状态
		async animationfinish(e) {
			let current = e.detail.current;
			this.$refs.uTabs.setFinishCurrent(current);
			this.swiperCurrent = current;
			this.current = current;
		},
		async swiperChange(e) {
			this.posts = [];
			let current = e.detail.current;
			const posts = await getPosts({
				params: {
					categories: this.list[current].id
				}
			});
			this.posts = posts;
		},
		// scroll-view到底部加载更多
		onreachBottom() {},
		openDetail(post) {
			uni.navigateTo({
				url: `/pages/posts/index?id=${post.id}`
			});
		}
	}
};
</script>

<style></style>
